#!/usr/bin/env python
# encoding: utf-8


"""
@version : v4.5
@author  : 
@license : 
@contact : ****@massclouds.com
@site    : http://blog.csdn.net/***
@software: PyCharm
@file    : test2.py.py
@time    : 16-10-10 下午12:26
"""
# !/bin/python
import base64, httplib, json
import traceback
import urllib


def remote_https_request(host='127.0.0.1', port='443', path=None, data=None,
                         method='GET', headers=None, timeout=1000):
    #f_headers = {'Content-Type': 'application/x-www-form-urlencoded',
    f_headers = {'Content-Type': 'application/json',
                 'Accept': 'application/json'}
    if headers:
        f_headers.update(headers)
    # verify if HTTPSConnection has context parameter
    try:
        conn = httplib.HTTPSConnection(host, port, timeout=timeout)
        params_data = None
        if data:
            #params_data = urllib.urlencode(data)
            params_data = json.dumps(data)
        conn.request(method, path, params_data if data else None,
                     f_headers)
        res = conn.getresponse()
        return json.loads(res.read())
    except:
        print traceback.format_exc()


def test_login():
    # login
    #host = '192.168.8.13'
    host = '192.168.100.144'
    port = 8000

    #data = {'username': 'jc', 'password': '123456', 'eauth': 'pam'}
    data = {'username': 'mass', 'password': 'mass', 'eauth': 'pam'}
    res = remote_https_request(host=host, port=port, path='/login', method='POST', data=data)
    token = res.get('return')[0].get('token')
    print token

    #data = {'method': 'ip_addrs', 'mid': 'vm-win7-01'}
    data = {'method': 'ip_addrs', 'mid': 'vm_win7_01'}
    info = remote_https_request(host=host, port=port,
                                path='/network',
                                headers={'X-Auth-Token': token},
                                data=data,
                                method='POST')
    print info
    return info["return"]


if __name__ == '__main__':
    import os

    try:
        infoList = test_login()
        if infoList.__len__() > 0:
            #print infoList[0][u'vm-win7-01']
            print infoList[0][u'vm_win7_01']
            ipList = infoList[0][u'vm_win7_01']
            if ipList.__len__() > 0:
                os.system("mcp_client -h %s -p 8888" % ipList[0])
    except Exception as e:
        print e.message
